<template>
  <div>
    <!--<div class="list-btn">
      渠道编号: <Input v-model.trim="params.channelCode" placeholder="请输入渠道编号" style="width: 200px" clearable @keyup.enter.native="getList(url)" />
    </div>
    <div class="list-btn">
      渠道名称: <Input v-model.trim="params.channelName" placeholder="请输入渠道名称" style="width: 200px" clearable @keyup.enter.native="getList(url)" />
    </div>-->
    <div class="list-btn">
      渠道:
      <Select style="width:200px"  v-model="params.channelCode" >
        <!-- <Option value=' '>全部</Option> -->
        <Option v-for="(item,index) in channelCodeList" :value="item.channelCode" :key="index">{{ item.channelName }}</Option>
      </Select>
    </div>
    <div class="list-btn">
       状态：
       <Select clearable style="width:200px" v-model="params.status" placeholder="全部">
        <Option value=' '>全部</Option>
        <Option :value=0>下架</Option>
        <Option :value=1>上架</Option>
      </Select>
    </div>
    <div class="list-btn">
      <Button type="primary" @click="getList(url,'refresh')">搜索</Button>
      <Button type="primary" style="margin-left: 10px;" @click="showModal.isShow=true;type='新增';resetValidate('formRole')">新增</Button>
    </div>
    <page-list :listTitle="listTitle" :list="list" :loading="loading" @selectItem="ids = $event;"></page-list>
    <page-button :current="params.pageCurrent"  :total="total" @changePageNum="params.pageCurrent = $event; getList(url)" @changePageSize="params.pageLimit = $event; getList(url)"></page-button>
    <Modal
      v-model="showModal.isShowUser"
      title="用户分配"
      :loading="loading">
      <form>
        <CheckboxGroup v-model="roleIdStr" >
          <div v-for="item in roleIdStrList">
            <Checkbox size="large" style="display: block;"  :label="item.id">{{`${item.userAccount} -- ${item.userName}`}}</Checkbox>
          </div>
        </CheckboxGroup>
      </form>
      <div style="margin-left: 350px;">
        <Button @click="showModal.isShowUser = false;">取消</Button>
        <Button type="primary" @click.prevent="roleUpdateData">确定</Button>
      </div>
    </Modal>
    <Modal
      v-model="showModal.isShow"
      :title="`${type}渠道`"
      width="500px"
      :loading="loading">
      <Form ref="formRole" :rules="ruleValidate" :model="formRole" :label-width="80">
       <!-- <FormItem label="渠道编号" prop="channelCode">
          <Input v-model="formRole.channelCode" placeholder="请输入" style="width:200px"></Input>
        </FormItem>-->
        <FormItem label="渠道名称" prop="channelName">
          <Input v-model="formRole.channelName" placeholder="请输入" style="width:200px"></Input>
        </FormItem>
       <!-- <FormItem label="渠道Url" prop="channelUrl">
          <Input v-model="formRole.channelUrl" placeholder="请输入" style="width:200px"></Input>
        </FormItem>-->
        <!--<FormItem label="状态" prop="status">
          <Select clearable v-model="formRole.status" placeholder="请选择" style="width:200px">
            <Option :value=0>下架</Option>
            <Option :value=1>发布</Option>
          </Select>
        </FormItem>-->
        <FormItem label="备注">
          <Input v-model="formRole.remarks" type="textarea" :autosize="{minRows: 3,maxRows: 5}" />
        </FormItem>
      </Form>
      <div style="margin-left: 350px;">
        <Button @click="showModal.isShow = false;">取消</Button>
        <Button type="primary" @click="roleUpdate">确定</Button>
      </div>
    </Modal>

  </div>
</template>

<script>
  import listMixin from '../../mixin/list'
  import pageList from '../../template/listTemplate'
  import pageButton from '../../template/pageBtnTemplate'
  import confirmDialog from '../../template/confirmDialogTemplate'
  import uploadImg from '../../template/uploadImgs'
  import common from '../../mixin/common'
  export default {
    mixins:[listMixin,common],
    components: {
      pageList,
      pageButton,
      confirmDialog,
      uploadImg
    },
    data () {
      return {
        token:sessionStorage.getItem('token'),
        tag: {
          'title': '渠道管理',
          'path': '/work/channel/list'
        },
        roleIdStrList:[],
        roleIdStr:[],
        userId:'',
        listTitle: [
          /*{
            title: '渠道编号',
            key: 'channelCode',
            align:'left',
            minWidth:160
          },*/
          {
            title: '渠道名称',
            key: 'channelName',
            align:'center',
            minWidth:160,
            render:(h,params) => {
              return h('div', params.row.channelName ? params.row.channelName : "—")
            }
          },
          {
            title: '渠道Url',
            key: 'channelUrl',
            align:'left',
            minWidth:200,
            render:(h,params) => {
              return h('div', params.row.channelUrl ? params.row.channelUrl : "—")
            }
          },
          {
            title: '创建时间',
            key: 'createTime',
            align:'center',
            minWidth:180,
            render:(h,params) => {
              return h('div', params.row.createTime ? this.getLocalTime(params.row.createTime) : "—")
            }
          },
          /*{
            title: '更新时间',
            key: 'title',
            align:'center',
            minWidth:160,
            render:(h,params) => {
              return h('div', params.row.updateTime ? this.getLocalTime(params.row.updateTime) : "—")
            }
          },*/
          {
            title: '修改时间',
            key: 'updateTime',
            align:'center',
            minWidth:160,
            render:(h,params) => {
              return h('div',params.row.updateTime ? this.getLocalTime(params.row.updateTime) : '—')
            }
          },
          {
            title: '操作人',
            key: 'updatorName',
            align:'center',
            minWidth:100,
            render:(h,params) => {
              return h('div',params.row.updatorName?params.row.updatorName:'—')
            }
          },
          {
            title: '状态',
            key: 'status',
            align:'center',
            minWidth:100,
            render:(h,params) => {
              let status = '';
              let btnType = '';
              switch (params.row.status){
                case 0 :
                  status = '已下架';
                  btnType = 'error';
                  break;
                case 1:
                  status = '已上架';
                  btnType = 'success';
                  break;
              }
              return h('Button',{
                props: {
                  type: btnType,
                  size: 'small'
                }
              }, status)

            }
          },
          /*{
            title: '备注',
            key: 'remarks',
            align:'left',
            minWidth:200,
            align:'center',
            render:(h,params) => {
              return h('div', params.row.remarks ? params.row.remarks : "—")
            }
          },*/
          {
            title: '操作',
            key: 'action',
            width: 200,
            align: 'center',
            render: (h, params) => {
               let btnType = '';
              if(params.row.status == 0){//下架
                btnType = '发布'
              }else if(params.row.status == 1){ //发布
                btnType = '下架'
              }
              return h('div', [
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.showModal.isShowUser = true;
                      this.title = params.row.userName ? params.row.userName : '用户分配';
                      this.getRole(params.row.id);
                      this.userId = params.row.id;
                      // console.log(params)
                    }
                  }
                }, '用户分配'),
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.showModal.isShow = true;
                      this.resetValidate('formRole');
                      this.type = '编辑';
                      this.formRole = JSON.parse(JSON.stringify(params.row))
                    }
                  }
                }, '编辑'),
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '提示',
                        content: `<p>确定要${btnType}吗?</p>`,
                        onOk: () => {
                          let status = '';
                          if(params.row.status == 0){
                            status = 1
                          }else {
                            status = 0
                          }
                           let data = {
                            // channelCode: params.row.channelCode,
                            channelName:  params.row.channelName,
                            //channelUrl:  params.row.channelUrl,
                            status: status,
                            remarks: params.row.remarks,
                            id : params.row.id
                          };
                            this.$post('/bkchannel/modify', data)
                            .then((res) => {
                              if(res.code === 0){
                                this.$Message.success(`${btnType}成功！`);
                                this.getList(this.url);
                              }
                            }, (err) => {
                              console.log(err);
                            })
                        },
                        onCancel: () => {
                        }
                      });
                    }
                  }
                }, btnType),
              ]);
            }
          }
        ],
        url:'bkchannel/list',
        nameListUrl: '',
        params: {
          pageCurrent: 1,
          pageLimit: 10
        },
        channelStr:[],
        showModal: {
          isShow: false,
          isShowUser: false
        },
        formRole: {
          status:1
        },
        type: '',
        ruleValidate: {
          // channelCode: [
          //   { required: true, message: '请填写渠道code', trigger: 'blur' }
          // ],
          channelName: [
            { required: true, message: '请填写渠道名称', trigger: 'blur' }
          ],
          /*channelUrl: [
            { required: true, message: '请填写渠道Url', trigger: 'blur' }
          ],*/
          /*status: [
            { required: true, message: '请选择标识', trigger: 'blur',type:'number' }
          ]*/
        },
        uploadData: {}
      }
    },
    created(){
      this.getChannel();
    },
    methods: {
      getRole(id){
        this.roleIdStr = [];
        this.channelStr = [];
        let params = {
          channelId: id,
          token: sessionStorage.getItem('token')
        }
        let _this = this;
        this.$post('/operation/channleList', params)
          .then((res) => {
            if(res.code === 0){
              this.roleIdStrList = res.data.roleList;
              let userRoleList = [];
              userRoleList = res.data.channelRoleList;
              console.log(this.userRoleList,'userRoleList')

              // console.log(res.data.userRolelist,'data.userRolelist')
              // console.log(userRoleList,'userRolelist')
              if(userRoleList.length>0){
                userRoleList.map((item) => {
                  this.roleIdStr.push(item.userId);
                  this.channelStr.push({roleId:item.roleId,channelId:item.channelId,channelCode:item.channelCode})
                })

              }else{
                this.roleIdStr = [];
                this.channelStr = [];
              }
              // console.log(this.roleIdStr,'roleIdStr')
            }
          })
      },
      roleUpdateData () {
        let params = {
          channelId: this.userId,
          userIdStr: this.roleIdStr.join(',')
        };
        this.$post('/operation/saveOrUpdate', params)
          .then((res) => {
            if(res.code == 0){
              // console.log(res.data)
              this.showModal.isShowUser = false;
              this.$Message.success('提交成功！');
            }else if(res.code ==1){
              this.$Message.error('当前账号已存在！');
            }
          }, (err) => {
            console.log(err);
          })
      },
      roleUpdate() {
        this.$refs['formRole'].validate((valid) => {
          if (valid) {
            let url = '';
            let data = {
              // channelCode: this.formRole.channelCode,
              channelName: this.formRole.channelName,
              //channelUrl: this.formRole.channelUrl,
              status: this.formRole.status,
              remarks: this.formRole.remarks,
            };
            if(this.type == '新增'){
              url = '/bkchannel/append';
            }else{
              data.id = this.formRole.id;
              url = '/bkchannel/modify';
            }
            this.$post(url, data)
              .then((res) => {
                if(res.code === 0){
                  console.log(res.data)
                  this.showModal.isShow = false;
                  this.$Message.success(`${this.type}成功！`);
                  this.getList(this.url);
                }
              }, (err) => {
                console.log(err);
              })
          }

        })
      },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .list-btn{
    margin-bottom: 5px;
    margin-right: 5px;
    display: inline-block;
  }
  .refresh-btn{
    float: right;
  }
  /deep/ .ivu-modal-footer{
    display: none;
  }
</style>
